import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import party from './../../images/party.png'
import party_org from './../../images/party_org.png'
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';

const FormItem = Form.Item;
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ party_member, loading, global }) => ({
  party_member,
  global,
  loading: loading.models.party_member,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      party_member: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        party_member: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'party_member/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'party_member/changeLoaded',
          });
          dispatch({
            type: 'party_member/changeTableY',
          });
        },
      });

    }
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'party_member/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'party_member/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'party_member/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      party_member: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>

          <FormItem label="党员姓名">
            {getFieldDecorator('name', {
              initialValue: searchParams.name,
            })(<Input style={{ width: '150px' }} placeholder="请输入"/>)}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            find(this.permissions, { name: 'party_member_edit' }) &&
            <Button
              icon="user-add"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              添加党员
            </Button>
          }
        </FormItem>

      </Form>
    );
  }

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    for(let key in formValues){
      if(key.indexOf('time')>=0 && formValues[key]){
        formValues[key]=moment( formValues[key]).format('YYYY-MM-DD')
      }
    }
    this.props.dispatch({
      type: 'party_member/add',
      payload: {
        ...formValues,

        type:1,
      },
      callback() {
        message.success('添加党员成功');
        that.setState({
          addModal: false,
        });
        const {
          party_member: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      username: '',
      page: 1,
      per_page: 30,
    });
  };

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const that = this;
    for(let key in formValues){
      if(key.indexOf('time')>=0 && formValues[key]){
        formValues[key]=moment( formValues[key]).format('YYYY-MM-DD')
      }
    }
    this.props.dispatch({
      type: `party_member/edit`,
      payload: {
        ...formValues,
        id: this.state.editRecord.id,
        type:1,
      },
      callback() {
        message.success('修改党员成功');
        that.setState({
          editModal: false,
        });
        const {
          party_member: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };
  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `party_member/remove`,
      payload: { id },
      callback: () => {
        message.success('删除党员成功');
        const {
          party_member: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      party_member: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen: true,
        formatter: (event) => {
          const {
            party_member: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '党员姓名',
        frozen: true,
        width: 160,
        key: 'name',
        formatter: (event) => {
          return <Fragment><img src={party} style={{width:'22px',height:'22px',marginRight:'5px'}} alt=""/>{event.value}</Fragment>;
        },
      },
      {
        name: '党员组织',
        frozen: true,
        width: 160,
        key: 'organization_name',
        formatter: (event) => {
          if(event.value){
            return <Fragment><img src={party_org} style={{width:'22px',height:'22px',marginRight:'5px'}} alt=""/>{event.value}</Fragment>;
          }else{
            return  ''
          }
        },
      },
      {
        name: '党内职务',
        width: 150,
        key: 'party_position',
      },
      {
        name: '行政职务',
        width: 160,
        key: 'position',
      },
      {
        name: '籍贯',
        width: 160,
        key: 'hometown',
      },
      {
        name: '民族',
        width: 120,
        key: 'nationality',
      },
      {
        name: '每月党费',
        width: 100,
        key: 'party_fee',
      },
    /*  {
        name: '是否已缴当月党费',
        key: 'role_na1m22232e',
        width: 140,
      },*/
      {
        name: '操作',
        width: 200,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            find(this.permissions, { name: 'party_member_edit' }) &&
              <Fragment>
                <Button
                  className={'btn-cyan'}
                  type="primary"
                  icon="edit"
                  size="small"
                  onClick={(e) => {
                    this.setState({
                      editRecord: event.row,
                      editModal: true,
                    });
                  }
                  }
                >编辑
                </Button>
                <Button
                  type="danger"
                  size="small"
                  icon="delete"
                  onClick={(e) => {
                    confirm({
                      title: `确定要删除党员${event.row.name}吗?`,
                      content: '请谨慎操作！',
                      okText: '确定',
                      okType: 'danger',
                      cancelText: '取消',
                      centered: true,
                      maskClosable: true,
                      onOk() {
                        that.handleDelete(event.row.id);
                      },
                      onCancel() {
                        console.log('Cancel');
                      },
                    });
                  }
                  }
                >删除
                </Button>
              </Fragment>

          }

        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>党员管理</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <div className={'table-data-content'}>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'party_member/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }} meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal" title="添加党员"/>}
        className="addModal"
        visible={this.state.addModal}
        centered
        width={1100}
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 : ${this.state.editRecord.name}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        width={1100}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          wrappedComponentRef={(inst) => this.EditForm = inst}/>
      </Modal>
    </div>;
  }
}

export default BasicList;
